package com.ruicar.afs.cloud.image.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruicar.afs.cloud.bizcommon.rules.service.AfsRuleInfoService;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.image.condition.ComAttachmentRuleCondition;
import com.ruicar.afs.cloud.image.entity.ComAttachmentManagement;
import com.ruicar.afs.cloud.image.entity.ComAttachmentRule;
import com.ruicar.afs.cloud.image.enums.AttachmentClassEnum;
import com.ruicar.afs.cloud.image.enums.IsEnableRuleEnum;
import com.ruicar.afs.cloud.image.enums.RuleStateEnum;
import com.ruicar.afs.cloud.image.enums.SynchronizationStateEnum;
import com.ruicar.afs.cloud.image.mapper.ComAttachmentRuleMapper;
import com.ruicar.afs.cloud.image.service.ComAttaManageService;
import com.ruicar.afs.cloud.image.service.ComAttachmentRuleService;
import com.ruicar.afs.cloud.image.vo.ComAttachmentCascaderVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description:
 * @Author: fangchenliang
 * @Date: 2020/5/15 20:15
 */
@RestController
@AllArgsConstructor
@RequestMapping("/manage")
@Api(value = "image", description = "影像类型管理模块")
public class ComAttaManageController {
    private ComAttaManageService comAttaManageService;
    private ComAttachmentRuleService ruleService;
    private ComAttachmentRuleMapper ruleMapper;
    private AfsRuleInfoService afsRuleInfoService;

    @GetMapping(value = "/getAttCategoriesList")
    @ApiOperation(value = "获取影像件大类")
    public IResponse<List<ComAttachmentManagement>> getAttCategoriesList() {
        List<ComAttachmentManagement> categoriesList = comAttaManageService.list();

        int level = 0;//影像件层级等于0——根目录
        List<ComAttachmentManagement> attCategories = categoriesList
                .stream()
                .filter(comAttachmentManagement -> comAttachmentManagement.getAttachmentClass() == level)
                .sorted(Comparator.comparing(ComAttachmentManagement::getSortOrder))
                .collect(Collectors.toList());
        attCategories.forEach(comAttachmentManagement -> {
            CollectChildAttachment(comAttachmentManagement, categoriesList);
        });
        return new IResponse<List<ComAttachmentManagement>>().setData(attCategories);
    }

    @GetMapping(value = "/getSubCategoriesList")
    @ApiOperation(value = "根据大类编号获取影像件组小类详细信息")
    public IResponse<IPage<ComAttachmentManagement>> getSubCategoriesList(@RequestParam(required = false) String parentId, @RequestParam(name = "pageNumber") int pageNumber, @RequestParam(name = "pageSize") int pageSize) {
        List list = new ArrayList();
        list.add(1);
        list.add(2);
        list.add(3);
        IPage<ComAttachmentManagement> categoriesList = comAttaManageService.page(new Page(pageNumber, pageSize),Wrappers.<ComAttachmentManagement>query().lambda()
                        .eq(StringUtils.isNotEmpty(String.valueOf(parentId)), ComAttachmentManagement::getParentId, parentId).in(ComAttachmentManagement::getAttachmentClass,list).orderByAsc(ComAttachmentManagement::getSortOrder)
        );
        return IResponse.success(categoriesList);
    }

    private void CollectChildAttachment(ComAttachmentManagement comAttachmentManagement, List<ComAttachmentManagement> allAttachmentManagement) {
        List<ComAttachmentManagement> children = allAttachmentManagement
                .stream()
                .filter(child -> comAttachmentManagement.getId().equals(child.getParentId()))
                .sorted(Comparator.comparing(ComAttachmentManagement::getSortOrder))
                .collect(Collectors.toList());
        children.forEach(child -> {
            CollectChildAttachment(child, allAttachmentManagement);
        });
        comAttachmentManagement.setChildren(children);
    }

    @RequestMapping(value = "/addAttachment", method = RequestMethod.POST)
    @ApiOperation(value = "附件新增")
    public IResponse<Boolean> addAttachment(@RequestBody ComAttachmentManagement attachmentManagement) {
        ComAttachmentManagement management = comAttaManageService.getById(attachmentManagement.getId());
        if (ObjectUtil.isNull(management)) {
            management = new ComAttachmentManagement();
        }
        BeanUtil.copyProperties(attachmentManagement, management);
        if (AttachmentClassEnum.SUBCLASS.getCode() == attachmentManagement.getAttachmentClass()) {
            management.setItemNum(1);
        }
        management.setSynchronizationState(SynchronizationStateEnum.CREATE.getCode());
        comAttaManageService.saveOrUpdate(management);
        /**如果存在null，需要重新set*/
        if(management.getArchiveClass()==null){
            comAttaManageService.update(Wrappers.<ComAttachmentManagement>lambdaUpdate().eq(ComAttachmentManagement::getId,management.getId())
                    .set(ComAttachmentManagement::getArchiveClass,null));
        }
        if(management.getEffectiveDateEnd()==null){
            comAttaManageService.update(Wrappers.<ComAttachmentManagement>lambdaUpdate().eq(ComAttachmentManagement::getId,management.getId())
                    .set(ComAttachmentManagement::getEffectiveDateEnd,null));
        }
        if(management.getUniqueCode()==null){
            comAttaManageService.update(Wrappers.<ComAttachmentManagement>lambdaUpdate().eq(ComAttachmentManagement::getId,management.getId())
                    .set(ComAttachmentManagement::getUniqueCode,null));
        }
        /**更新父类内涵项目数*/
        List<ComAttachmentManagement> list = comAttaManageService.list((Wrappers.<ComAttachmentManagement>query().lambda().eq(ComAttachmentManagement::getParentId, String.valueOf(management.getParentId()))));
        ComAttachmentManagement parentManagement = comAttaManageService.getById(management.getParentId());
        parentManagement.setItemNum(list.size());
        comAttaManageService.updateById(parentManagement);
        return new IResponse().setData(true);
    }

    @RequestMapping(value = "/updateAttachmentManage", method = RequestMethod.POST)
    @ApiOperation(value = "附件启用停用")
    public IResponse<Boolean> updateAttachmentManage(@RequestBody ComAttachmentManagement attachmentManagement) {
        ComAttachmentManagement management = comAttaManageService.getById(attachmentManagement.getId());
        if (StringUtil.isEmpty(management.getIsEnableRule()) || IsEnableRuleEnum.NO.getCode().equals(management.getIsEnableRule())) {
            management.setIsEnableRule(IsEnableRuleEnum.YES.getCode());
        } else {
            management.setIsEnableRule(IsEnableRuleEnum.NO.getCode());
        }
        comAttaManageService.saveOrUpdate(management);
        return new IResponse().setData(true);
    }

    @PostMapping(value = "/getOneAttachment/{id}")
    @ApiOperation(value = "根据ID查询附件信息")
    public IResponse<ComAttachmentManagement> getOneAttachment(@PathVariable String id) {
        ComAttachmentManagement attachmentManagement = comAttaManageService.getById(id);
        return IResponse.success(attachmentManagement);
    }

    @RequestMapping(value = "/searchAttachment", method = RequestMethod.GET)
    @ApiOperation(value = "搜索附件名称")
    public IResponse<List<ComAttachmentManagement>> searchAttachment(@RequestParam String title) {
        List<ComAttachmentManagement> list = comAttaManageService.findByAttachmentName(title);
        return new IResponse<List<ComAttachmentManagement>>().setData(list);
    }

    @RequestMapping(value = "/addAttachmentRule", method = RequestMethod.POST)
    @ApiOperation(value = "新增附件规则信息")
    public IResponse<ComAttachmentRule> addAttachmentRule(@RequestBody ComAttachmentRule rule) {
        ComAttachmentRule attachmentRule = ruleService.getById(rule.getId());
        if (ObjectUtil.isNull(attachmentRule)) {
            attachmentRule = new ComAttachmentRule();
            attachmentRule.setAttachmentId(rule.getAttachmentId());
            attachmentRule.setRuleName(rule.getRuleName());
            attachmentRule.setRuleValue(rule.getRuleValue());
            attachmentRule.setRuleState(RuleStateEnum.EFFECTIVE.getCode());
        }
        attachmentRule.setRuleName(rule.getRuleName());
        attachmentRule.setRuleValue(rule.getRuleValue());
        ruleService.saveOrUpdate(attachmentRule);
        return IResponse.success(rule);
    }

    @GetMapping(value = "/queryAttachmentRule")
    @ApiOperation(value = "查询附件规则信息")
    public IResponse<IPage<ComAttachmentRuleCondition>> queryAttachmentRule(@RequestParam(name = "pageNumber") int pageNumber, @RequestParam(name = "pageSize") int pageSize, @RequestParam(required = false) String attachmentId) {
        ComAttachmentRuleCondition ruleCondition = new ComAttachmentRuleCondition();
        ruleCondition.setAttachmentId(attachmentId);
        IPage<List<ComAttachmentRuleCondition>> list = ruleMapper.getValueInfo(new Page(pageNumber, pageSize), ruleCondition);
        return IResponse.success(list);
    }

    @RequestMapping(value = "/updateAttachmentRule", method = RequestMethod.POST)
    @ApiOperation(value = "修改规则状态")
    public IResponse<ComAttachmentRule> updateAttachmentRule(@RequestBody ComAttachmentRuleCondition condition) {
        ComAttachmentRule rule = ruleService.getById(condition.getId());
        if (RuleStateEnum.EFFECTIVE.getCode().equals(condition.getRuleState())) {
            afsRuleInfoService.activeRule(condition.getRuleId());
            rule.setRuleState(RuleStateEnum.INVALID.getCode());
        } else if (RuleStateEnum.INVALID.getCode().equals(condition.getRuleState())) {
            afsRuleInfoService.deActiveRule(condition.getRuleId());
            afsRuleInfoService.expiredRule(condition.getRuleId());
            rule.setRuleState(RuleStateEnum.EFFECTIVE.getCode());
        } else {
            rule.setRuleState(RuleStateEnum.EFFECTIVE.getCode());
        }
        ruleService.saveOrUpdate(rule);
        return new IResponse().setData(true);
    }

    @GetMapping(value = "/searchByParentId")
    @ApiOperation(value = "附件查询")
    public IResponse<List<ComAttachmentManagement>> searchByParentId(@RequestParam(name = "pageNumber") int pageNumber, @RequestParam(name = "pageSize") int pageSize, @RequestParam(required = false) String parentId) {
        IPage<List<ComAttachmentManagement>> list = comAttaManageService.page(new Page(pageNumber, pageSize), Wrappers.<ComAttachmentManagement>query().lambda().eq(ComAttachmentManagement::getParentId, parentId).orderByAsc(ComAttachmentManagement::getSortOrder));
        return IResponse.success(list);
    }

    @PostMapping(value = "/getComAttachmentCascader")
    @ApiOperation(value = "获取大类小类前端级联列表")
    public IResponse<List<ComAttachmentCascaderVo>> getComAttachmentCascader(@RequestParam(name="busiNode") String busiNode) {
        // 查询大类
        List<ComAttachmentManagement> categoriesList = comAttaManageService.list(
                Wrappers.<ComAttachmentManagement>query().lambda().eq(ComAttachmentManagement::getAttachmentClass, AttachmentClassEnum.CATEGORY.getCode())
                        .eq(!ObjectUtils.isEmpty(busiNode),ComAttachmentManagement::getBusiNode,busiNode));
        // 组装数据
        List<ComAttachmentCascaderVo> list = categoriesList.stream().map(categories -> {
            ComAttachmentCascaderVo level1Vo = new ComAttachmentCascaderVo();
            level1Vo.setValue(String.valueOf(categories.getId()));
            level1Vo.setLabel(categories.getAttachmentName());
            // 查询大类所属小类
            List<ComAttachmentManagement> smalls = comAttaManageService.list(
                    Wrappers.<ComAttachmentManagement>query().lambda()
                            .eq(ComAttachmentManagement::getParentId, categories.getId())
                            .eq(ComAttachmentManagement::getAttachmentClass, AttachmentClassEnum.SUBCLASS.getCode()));
            List<ComAttachmentCascaderVo> smallVos = smalls.stream().map(small -> {
                ComAttachmentCascaderVo level3Vo = new ComAttachmentCascaderVo();
                level3Vo.setValue(String.valueOf(small.getId()));
                level3Vo.setLabel(small.getAttachmentName());
                return level3Vo;
            }).collect(Collectors.toList());
            // 加入大类
            level1Vo.setChildren(smallVos);
            return level1Vo;
        }).collect(Collectors.toList());

        return IResponse.success(list);
    }
}
